package com.hall.service;

import com.hall.pojo.Userschedule;
import com.hall.utils.TimeThisWeekend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
 * 日程表模块自动添加日程的定时任务
 */
@Service
public class QuartzServiceImpl {
    @Autowired
    private ScheduleService scheduleService;
    @Scheduled(cron = "0 15 00 ? * MON ") //cron表达式(每周一凌晨00:15分执行一次)*/
    public void quartz(){
        System.out.println("定时添加用户日程任务开启>>>>>>>>>>>>>>");
        System.out.println("开始设置用户日程");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        Date date = null;
        try {
            date = df.parse(df.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String thisSunday = TimeThisWeekend.getNextSevenWeek(date); //获取当前周末日期
        List<String> sunday = TimeThisWeekend.getNextWeekDay(thisSunday);//下周周1-7日期
        List<String> days = TimeThisWeekend.getWeekDay(); //本周周1-7日期
        List<String> allUserSch = scheduleService.findHaveScheduleUser();//查询了所有有日程的用户
        for(String userId : allUserSch ){                                //获取当前用户的第二周日程
          List<Userschedule> schedu =  scheduleService.GetNextSchedule(userId,days.get(0)); //每位用户的本周日程
            for(int i=0;i<=schedu.size()-1;i++){
                Userschedule s= schedu.get(i);
                //检查自动添加日程的当条日程是否有已约事件("状态为3"),若有,修改为0
                String cks = s.getTimeconfig();
                if(cks.contains("3")){
                   cks=cks.replace("3","0");
                   s.setTimeconfig(cks);
                }
                String userName = scheduleService.getUserName(s.getUserid());//避免自动添加存在用户名修改导致不一样的问题
                scheduleService.setNext(new Userschedule().setUserid(s.getUserid()).setUsername(userName).setScheduledate(sunday.get(i)).setTimeconfig(s.getTimeconfig()));
            }
        }
    }
}
